<?php
class BlogAction extends Action {
	private $filter;
	public function _initialize() {
		vendor ( 'libs.SamLib.sampeng' );
		$this->assign ( 'mid', ( string ) $this->mid );
		$this->assign ( 'uid', intval ( $_GET ['uid'] ) );
		$allowAction = array ('apply', 'applying', 'addApply','edit','doEdit','deleteBlog','downDigOrder','upDigOrder' );
		$status = $this->createFactory ( 'BlogApply' )->checkUserApply ( $this->mid );
		
		if (! in_array ( ACTION_NAME, $allowAction )) {
			if (! isset ( $status ))
				$this->redirect ( 'home/blog/apply' );
			if ($status === "0")
				$this->redirect ( 'home/blog/applying' );
		}
		
		if (ACTION_NAME == 'apply') {
			if ($status === "0")
				$this->redirect ( 'home/blog/applying' );
			if($status  === '1')
				$this->redirect ( 'home/blog/blogList' );
		}
		if (ACTION_NAME == 'applying') {
			if ($status === "1")
				$this->redirect ( 'home/blog/blogList' );
		}
		
		$this->setTitle( L('blog_my')." - ".L('blog_space') );	
	}
	
	public function downDigOrder(){
		$map ['blogId'] = is_array($_REQUEST['id'])?array('in',$_REQUEST ['id']):$_REQUEST['id']; //要删除的id;
		
		if(!is_array($map['blogId'])){
			$blogUid = $this->createFactory ( 'BlogInfo' )->where($map)->getField('uid');
			$admin = model('UserGroup')->isAdmin($this->mid);
			
			
			if ($this->mid != $blogUid && $admin == false) {
				$this->error (L('blog_not_rule'));
			}
		}else{
			$admin = model('UserGroup')->isAdmin($this->mid);
			if ( $admin == false) {
				$this->error (L('blog_not_rule'));
			}
		}
		
		
	
		
		$save['isHot'] = 1;
		$result = $this->createFactory ( 'Blog' )->where($map)->save($save);
		if (false != $result) {
			$jumpUrl = U('space/index/index');
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->success ( L('blog_edit_success') );
		} else {
			$jumpUrl = U ( 'blog/index/detail', 'id=' . $_REQUEST ['id'].'&uid='.$blogUid );
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->error ( L('blog_edit_field') );
		}
	}
	
	public function upDigOrder(){
		$map ['blogId'] = is_array($_REQUEST['id'])?array('in',$_REQUEST ['id']):$_REQUEST['id']; //要删除的id;
		
		if(!is_array($map['blogId'])){
			$blogUid = $this->createFactory ( 'BlogInfo' )->where($map)->getField('uid');
			$admin = model('UserGroup')->isAdmin($this->mid);
			
			
			if ($this->mid != $blogUid && $admin == false) {
				$this->error ( L('blog_not_rule') );
			}
		}else{
			$admin = model('UserGroup')->isAdmin($this->mid);
			if ( $admin == false) {
				$this->error ( L('blog_not_rule') );
			}
		}
		
		$save['isHot'] = 0;
		$result = $this->createFactory ( 'Blog' )->where($map)->save($save);
		
		if (false != $result) {
			$jumpUrl = U('space/index/index');
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->success ( L('blog_edit_success') );
		} else {
			$jumpUrl = U ( 'blog/index/detail', 'id=' . $_REQUEST ['id'].'&uid='.$blogUid );
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->error ( L('blog_edit_field') );
		}
	}
	
	public function addApply() {
		$uid = $this->mid;
		$info = $this->cleanString ( $_POST ['info'] );
		$result = $this->createFactory ( 'BlogApply' )->addApply ( $uid, $info );
		if ($result) {
			$jumpUrl = U ( 'home/user/index', 'uid=' . $this->mid );
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->success ( L('blog_apply_success') );
		} else {
			$jumpUrl = U ( 'home/blog/apply' );
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->success ( L('blog_apply_success') );
		}
	}
	
	public function post() {
		//获取分类
		$cate = $this->createFactory ( 'BlogCategory' )->getUserCategory ( $this->mid );
		
		//头部导航
		$header = $this->setHeader ( L('blog_post_new_artice'), U ( 'home/blog/post' ), $this->mid );
		$this->assign ( 'headerList', implode ( " > ", $header ) );
		$this->assign ( 'category', $cate );
		$this->display ();
	}
	
	protected function setHeader($title = null, $url, $uid) {
		static $header;
		if (empty ( $header )) {
			if ($this->mid == $uid) {
				$list = U ( 'home/blog/blogList' );
				$word = L('blog_my');
				
				$space = U ( 'home/user/index', 'uid=0' );
				$word2 = L('blog_my_space');
			} else {
				$list = U ( 'space/blog/blogList', 'uid=' . $uid );
				$word = getUserName ( $uid ) . L('blog_who');
				
				$space = U ( 'space/view/index', 'uid=' . $uid );
				$word2 = getUserName ( $uid ) . L('blog_who_space');
			}
			$header [0] = "<a href='" . U ( 'space/index/index' ) . "'>".L('blog_index')."</a>";
			$header [1] = "<a href=" . $space . ">" . $word2 . "</a>";
			$header [2] = "<a href=" . $list . ">" . $word . "</a>";
		}
		if (! isset ( $title )) {
			return $header;
		}
		$header [] = "<a href=" . $url . ">" . $title . "</a>";
		
		return $header;
	}
	
	public function edit() {
		$id = $_GET ['id'];
		$uid = $_GET ['uid'];
		//获取分类
		
		$result = $this->createFactory ( 'BlogInfo' )->getBlogContent ( $id, $_GET ['how'], $uid, $this->mid, true );
		$cate = $this->createFactory ( 'BlogCategory' )->getUserCategory ( $result['uid'] );
		$admin = model('UserGroup')->isAdmin($this->mid);
		
		if ($this->mid != $result ['uid'] && $admin == false) {
			$this->error ( L('blog_not_rule') );
		}
		
		$this->assign ( 'data', $result );
		
		$this->assign ( 'category', $cate );
		$this->display ();
	}
	
	public function addCategory() {
		$cate = $this->createFactory ( 'BlogCategory' )->getCategory ( true );
		$this->assign ( 'category', $cate );
		$this->display ();
	}
	public function createFactory($name) {
		return D ( $name, 'blog' );
	}
	
	public function doAddCategory() {
		$data ['pid'] = intval ( $_POST ['pid'] );
		
		$data ['name'] = $this->htmlString ( $_POST ['name'] );
		$data ['uid'] = $this->mid;
		$result = $this->createFactory ( 'BlogCategory' )->addCategory ( $data );
		echo $result;
	}
	
	
	
	/**
	 * doDeleteblog
	 * 删除blog
	 * @access public
	 * @return void
	 */
	public function doDeleteblog() {
		
		$this->blog->id = $_REQUEST ['id']; //要删除的id;
		$result = $this->blog->doDeleteblog ( null, $this->mid );
		if (false != $result) {
			$this->redirect ( 'Index/my' );
		} else {
			$this->error ( L('blog_delete_field') );
		}
	}
	
	/**
	 * deleteCateFrame
	 * 删除分类时，转移其中的日志
	 * @access public
	 * @return void
	 */
	public function deleteCateFrame() {
		$id = $_GET ['id'];
		$category = $this->createFactory ( 'BlogCategory' )->getUserCategory ( $this->mid );
		foreach ( $category as $key => $value ) {
			if ($value ['id'] == $id)
				unset ( $category [$key] );
		}
		$this->assign ( 'category', $category );
		$this->display ();
	}
	
	/**
	 * deleteCategory
	 * 删除分类
	 * @access public
	 * @return void
	 */
	public function deleteCategory() {
		$data ['id'] = intval ( $_POST ['id'] );
		if (0 === $data ['id'])
			return false;
			
		//删除分类和将分类的日志转移到其他分类里
		isset ( $_POST ['toCate'] ) && ! empty ( $_POST ['toCate'] ) && $toCate = $_POST ['toCate'];
		
		echo $this->createFactory ( 'BlogCategory' )->deleteCategory ( $data, $toCate, $this->createFactory ( 'Blog' ) );
	}
	
	/**
	 * editCategory
	 * 修改分类
	 * @access public
	 * @return void
	 */
	public function editCategory() {
		$result = $this->createFactory ( 'BlogCategory' )->editCategory ( $_POST ['name'], $_POST ['cate'] );
		$jumpUrl = U ( 'home/blog/blogList' );
		$this->assign ( 'jumpUrl', $jumpUrl );
		$this->success ( L('blog_edit_success') );
	}
	
	/**
	 * doDeleteblog
	 * 删除blog
	 * @access public
	 * @return void
	 */
	public function deleteBlog() {
		
		$map ['blogId'] = is_array($_REQUEST['id'])?array('in',$_REQUEST ['id']):$_REQUEST['id']; //要删除的id;
		$blogInfo = $this->createFactory ('BlogInfo')->where($map)->field('uid,status')->find();
		
		$blogUid = $blogInfo['uid'];
		$admin = model('UserGroup')->isAdmin($this->mid);
		
		
		if ($this->mid != $blogUid && $admin == false) {
			$this->error ( L('blog_not_rule') );
		}
		
		if($blogInfo['status'] == 1){
				$result = $this->createFactory ( 'Blog' )->deleteBlog ( $map, $this->mid );
		}else{
				$save['status'] = 3;
				$result = $this->createFactory ('Blog')->where($map)->save($save);			
		}
		
		
		
		if (false != $result) {
			if($this->mid == $blogUid){
				$jumpUrl = U ( 'home/blog/blogList' );
			}else{
				$jumpUrl = U ( 'space/blog/blogList','uid='.$blogUid );
			}
			$result = model('UserCredit')->set($blogUid,'delete_blog');
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->success ( L('blog_delete_success') );
		} else {
			$jumpUrl = U ( 'blog/index/detail', 'id=' . $_REQUEST ['id'].'&uid='.$blogUid );
			$this->assign ( 'jumpUrl', $jumpUrl );
			$this->error ( L('blog_delete_field') );
		}
	}
	
	public function admin() {
		$cate = $this->createFactory ( 'BlogCategory' )->getCategory ( true );
		$userCate = $this->createFactory ( 'BlogCategory' )->getUserCategory ( $this->mid );
		$temp_cate = $this->createFactory ( 'BlogInfo' )->getCountByCategory ( $this->mid );
		$userCate = ArrayTools::join ( $userCate, $temp_cate, 'id' );
		$this->assign ( 'cate', $cate );
		$this->assign ( 'userCate', $userCate );
		$this->display ();
	}
	/**
	 * doAddblog
	 * 添加blog
	 * @access public
	 * @return void
	 */
	public function doAddBlog() {
		$this->_checkInput ();
		
		//处理发日志的数据
		$data = $this->__getPost (false);
		//添加日志
		$add = $this->createFactory ( 'Blog' )->addblog ( $data );
		if ($add) {
			$this->createFactory('Blog')->addTags ( $add, $data ['tags'],$this->mid,false);
			$jumpUrl = U ( 'blog/index/detail', "id={$add}&uid={$this->mid}" );
			
			//发送动态put($type,$title,$body,$uid='',$uname='',$fid=0);
			$body_data ['url'] = $jumpUrl;
			$body_data ['content'] = StringTools::left ( t ( $this->cleanString ( $data ['content'] ) ), 100 );
			
			$title_data ['title'] .= sprintf ( "<a href=%s>%s</a>", $body_data ['url'], $data ['title'] );
			
			service ( 'Feed' )->put ( "blog_post", $title_data, $body_data );
			model('UserCredit')->set($this->mid,'blog_add_blog');
			$this->assign ( 'jumpUrl', $jumpUrl );
			
			$this->success ( L('blog_add_success') );
		} else {
			$this->error ( L('blog_add_field') );
		}
	}
	
	public function doEdit() {
		$id = intval ( $_POST ['blogId'] );
		if ($this->createFactory ( 'BlogInfo' )->where ( 'blogId=' . $id )->count () == 0) {
			$this->error ( L('blog_not_exist') );
		}
		
		$blogUid = $this->createFactory('BlogInfo')->where('blogId='.$id)->getField('uid');
				$admin = model('UserGroup')->isAdmin($this->mid);
		
		
		if ($this->mid != $blogUid && $admin == false) {
			$this->error ( L('blog_not_rule') );
		}
		
		
		$this->_checkInput ();
		$data = $this->__getPost (true);
		
		$save = $this->createFactory ( 'Blog' )->saveBlog ( $data, $id );
		$jumpUrl = U ( 'blog/index/detail', "id={$id}&uid={$blogUid}" );
		$this->assign ( 'jumpUrl', $jumpUrl );
		if ($save) {
			$this->success ( L('blog_edit_success') );
		} else {
			$this->error ( L('blog_edit_field') );
		}
	}
	private function _checkInput() {
		$content = trim ( str_replace ( '&amp;nbsp;', '', $_POST ['content'] ) );
		//检查是否为空
		if (empty ( $_POST ['content'] ) || empty ( $content )) {
			$this->error ( L('blog_check_must_input') );
			//exit();
		}
		
		if (StringTools::length ( t ( $_POST ['title'] ) ) > 70) {
			$this->error ( L('blog_check_title_long') );
		}
		if ($_POST ['category'] == 0 || $_POST ['category'] == "noSelected") {
			$this->error ( L('blog_check_not_select_category') );
		}
	
	}
	
	public function getTags() {
		$content = t( $_POST ['content'] );
		$tag = service ( 'Tag' );
		$tag->setText ( $content );
		$tags = $tag->getTop ( 3 );
		echo $tags;
	}
	
	protected function cleanString($value, $type) {
		$this->filter = Security::getInstance ( $type );
		
		$this->filter->setTagsMethod ( false );
		
		return $this->filter->inputFilter ( $value );
	}
	protected function htmlString($value) {
		$this->filter = Security::getInstance ();
		$this->filter->setTagsMethod ( true );
		return $this->filter->inputFilter ( $value );
	}
	
	private function __wipeVerticalArray($array) {
		$result = array ();
		foreach ( $array as $key => $value ) {
			$temp = explode ( '|', $value );
			$result [$key] ['id'] = $temp [0];
			$result [$key] ['name'] = $temp [1];
		}
		return $result;
	
	}
	private function __getPost($edit) {
		//得到发日志人的名字
		//TODO 管理员修改日志
		if(!$edit){
			$userName = getUserName ( $this->mid );
			$data ['name'] = $userName;
			$data ['uid'] = $this->mid;
		}

		$data ['content'] = $_POST ['content'];
		
		$data ['category'] = intval ( $_POST ['category'] );
		$title = h($_POST ['title'],'string',false,false);
		$data ['title'] = ! empty ( $title ) ? $title : L('blog_not_title');
		$data ['tags'] = $_POST ['tags'];
		
		//处理attach数据
		$data ['attach'] = serialize ( $this->__wipeVerticalArray ( $_POST ['attach'] ) );
		if (empty ( $_POST ['attach'] ) || ! isset ( $_POST ['attach'] )) {
			$data ['attach'] = null;
		}
		return $data;
	}
	
	public function blogList() {
		if (isset ( $_GET ['uid'] )) {
			$uid = intval ( $_GET ['uid'] );
			$map ['uid'] = $uid;
		} else {
			$map ['uid'] = $this->mid;
			$uid = $this->mid;
		}
		
		if (isset ( $_GET ['category'] )) {
			$cate = intval ( $_GET ['category'] );
			$map ['category'] = $cate;
		}
		if (isset ( $_GET ['date'] )) {
			$map ['cTime'] = array ('BETWEEN', $this->getData ( str_replace('-','',$_GET ['date']) ) );
		}
		if (isset ( $_GET ['tagId'] )) {
			$map ['blogId'] = array ('in', $this->createFactory ( 'BlogTags' )->getBlogIdByTag ( intval ( $_GET ['tagId'] ) ) );
		}
		$map['status'] = array('in',array(1,2));
		
		$field = 'title,blogId,commentCount,readCount,cTime,cover,category,content,uid';
		$result = $this->createFactory ( 'BlogInfo' )->getBlogList ( $map, $field, $order, 20 );
		$this->setTitle(L('blog_my'));
		
		$data ['uid'] = $uid;
		$this->setRight ( $data );
		$this->assign ( $result );
		$this->display ();
	}
	
	private function setRight($result) {
		$showImageArray = array ('detail' );
		
		//判断是否是自己
		$my = $this->mid == $result ['uid'];
		$category = $this->createFactory ( 'BlogCategory' )->getUserCategory ( $result ['uid'] );
		//获取前10个标签
		$tags = $this->createFactory ( 'BlogTags' )->getTags ( 10, 'cTime', $result ['uid'] );
		$tags = implode ( ',', $tags );
		$tagsName = model ( 'Xtag' )->getTagName ( $tags );
		//博客统计
		//$sum = $this->createFactory('BlogInfo')->getBlogSum($this->mid,ACTION_NAME);
		

		//归档
		$date = date ( 'Ym', time () );
		$condition ['uid'] = $result ['uid'];
		 $condition['status'] = array('in',array(1,2));
		if (isset ( $_GET ['category'] ))
			$condition ['category'] = $_GET ['category'];
		if (isset ( $_GET ['tagId'] ))
			$condition ['blogId'] = array ('in', $this->createFactory ( 'BlogTags' )->getBlogIdByTag ( intval ( $_GET ['tagId'] ) ) );
		$date = self::paramData ( $date, 6, 'ts_blog', $condition );
		
		$data ['date'] = $date;
		$data ['sumer'] = $this->createFactory ( 'BlogInfo' )->getUserBlogCount ( $result ['uid'] );
		//处理归档链接
		$url = array ();
		$tagUrl = array ();
		
		$curl = APP_NAME . '/' . MODULE_NAME . '/blogList';
		
		$categoryUrl = $this->getRightUrl ( 'category', 'tagId', 'date', 'how', 'mid' );
		$tagUrl = $this->getRightUrl ( 'tagId', 'category', 'date', 'how', 'mid' );
		$url = $this->getRightUrl ( 'date', 'how', 'mid' );
		
		$tags = getBlogTags ( $tags, $tagsName, ' ', U ( $curl, $tagUrl ) );
		
		$this->assign ( $data );
		$this->assign ( 'right_tags', $tags );
		$this->assign ( 'right_category', $category );
		$this->assign ( 'show', in_array ( ACTION_NAME, $showImageArray ) );
		$this->assign ( 'url', U ( $curl, $url ) );
		$this->assign ( 'categoryUrl', U ( $curl, $categoryUrl ) );
		//将Tags换成链接
		$this->assign ( 'my', $my );
		$this->assign ( $result );
	}
	
	private function getRightUrl() {
		$url = array ();
		$data = func_get_args ();
		foreach ( $_GET as $key => $value ) {
			if (in_array ( $key, $data ) || $key === "app" || $key === "id")
				continue;
			$url [] = $key . '=' . $value;
		}
		return implode ( '&', $url );
	}
	
	/**
	 * paramData
	 * 解析日期
	 * @param mixed $date 当前时间（200905格式）
	 * @param mixed $object 需要查询数据的object名.
	 * @static
	 * @access private
	 * @return void
	 */
	private function paramData($date, $limit = 6, $tableName, $condition) {
		$result = D ( 'Blog' )->field('count(1) as count,from_unixtime(`cTime`,\'%Y-%m\') as day')->where($condition)->group('day')->order('day DESC')->findAll();
		$limit_time = array();
		foreach ( $result as $value ) {
			$limit_time [$value ['day']] ['count'] = $value ['count'];
			$limit_time [$value ['day']] ['content'] = $value['day'];
		}
		return $limit_time;
	}
	/**
	 * getData
	 * 处理归档查询的时间格式
	 * @param string $findTime 200903这样格式的参数
	 * @static
	 * @access protected
	 * @return void
	 */
	private function getData($findTime) {
		//处理年份
		$year = $findTime [0] . $findTime [1] . $findTime [2] . $findTime [3];
		//处理月份
		$month_temp = explode ( $year, $findTime );
		$month = $month_temp [1];
		//归档查询
		if (! empty ( $month )) {
			
			//判断时间.处理结束日期
			switch (true) {
				case (in_array ( $month, array (1, 3, 5, 7, 8, 10, 12 ) )) :
					$day = 31;
					break;
				case (2 == $month) :
					if (0 != $year % 4) {
						$day = 28;
					} else {
						$day = 29;
					}
					break;
				default :
					$day = 30;
					break;
			}
			//被查询区段开始时期的时间戳
			$start = mktime ( 0, 0, 0, $month, 1, $year );
			
			//被查询区段的结束时期时间戳
			$end = mktime ( 24, 0, 0, $month, $day, $year );
			
		//反之,某一年的归档
		} elseif (isset ( $year [4] )) {
			$start = mktime ( 0, 0, 0, 1, 1, $year );
			$end = mktime ( 24, 0, 0, 12, 31, $year );
		} else {
			//其他操作
		}
		
		return array ($start, $end );
	
	}
}
?>